package xx.services.entity.rest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;

import xx.db.sql.Table;
import xx.entity.bas.CategoryLink;
import xx.entity.bas.EntityExt;
import xx.entity.bas.EntityExtDefined;
import xx.entity.datum.Detail;
import xx.entity.datum.DetailValue;
import xx.entity.datum.Type;
import xx.services.Passport;
import xx.services.entity.inter.IDatumInterface;
import xx.util.string.Format;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * @author dengjinye,2011-2-18 $LastChangedDate$ $Author$
 */
@Path("/services/datum")
public class DatumRest extends Passport implements IDatumInterface
{

    public DatumRest(@Context
    HttpServletRequest request)
    {
        super(request);
        // TODO Auto-generated constructor stub
    }

    /**
     * 描述：获取实体的档案，包含扩展属性. <br>
     * 1.获取entity_id对应的所有档案 <br>
     * 2.获取entity_id下指定分类({type_id|keyword})对应的档案属性。 输入： 输出：档案JSON数据 [ { detail_id, entity_id, type_id,
     * rule, error, single, keyword, [ { value_id, attribute_id, title, value, rule, error,
     * datatype, opvalue } ] } ]
     * 
     * @param entityId
     * @return
     * @author dengjinye,2011-2-21
     */
    @GET
    @Path("/{entity_id}")
    public String getDatum(@PathParam("entity_id")
    long entityId)
    {
        try
        {
            Map<String, Object> resultMap = new HashMap<String , Object>();
            
            Detail detail = new Detail(qr, owner);
            detail.setEntityId(entityId);
            List<? extends Table> list = detail.getList();
            resultMap.put("datum", list);
            
            //获取entity的横向扩展属性（即entityExt）add by dengjinye 20130523
            CategoryLink categoryLink = new CategoryLink(qr, owner);
            categoryLink.setEntityId(entityId).load(CategoryLink.CATEGORY_ID);
            long categoryId = categoryLink.getCategoryId();
            
            EntityExtDefined entityExtDefined = new EntityExtDefined(qr, owner);
            entityExtDefined.setCategoryId(categoryId).load();
            
//            EntityExt entityExt = new EntityExt(qr, owner);
//            entityExt.setEntityId(entityId).load();
            resultMap.put("ext", entityExtDefined);
            
            return ok(resultMap);
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 描述：获取实体的档案 <br>
     * 1.获取entity_id对应的所有档案 <br>
     * 2.获取entity_id下指定分类({type_id|keyword})对应的档案属性。 输入： 输出：档案JSON数据 [ { detail_id, entity_id, type_id,
     * rule, error, single, keyword, [ { value_id, attribute_id, title, value, rule, error,
     * datatype, opvalue } ] } ]
     * 
     * @param entityId
     * @param typeId
     *            有两种可能值：type_id,keyword
     * @return
     * @author dengjinye,2011-2-21
     */
    @GET
    @Path("/{entity_id}/@type/{type_id}")
    public String getDatumByTypeId(@PathParam("entity_id")
    long entityId, @DefaultValue("")
    @PathParam("type_id")
    String typeId)
    {
        try
        {
            Detail detail = new Detail(qr, owner);
            detail.setEntityId(entityId);
            if (typeId.matches("\\d+"))
            {
                detail.setTypeId(Long.parseLong(typeId));
            }
            else
            {
                Type t = new Type(qr, owner);
                t.setKeyword(typeId).load(Type.TYPE_ID);
                detail.setTypeId(t.getTypeId());
            }

            List list = detail.getList();
            return ok(list);
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 描述：更新实体对应的属性值.<br>
     * 1.value json 属性值JSON数据，格式如下： <br>
     * [{value_id:number,value:string}]<br>
     * 
     * @param entityId
     * @return
     * @author dengjinye,2011-2-21
     */
    @PUT
    @Path("/{entity_id}")
    public String updateDatum(@PathParam("entity_id")
    long entityId, @FormParam("value")
    String value)
    {
        try
        {
            JsonParser parser = new JsonParser();
            JsonArray ja = parser.parse(value).getAsJsonArray();
            DetailValue dv = new DetailValue(qr, owner);
            int count = 0;
            for (JsonElement je : ja)
            {
                JsonObject jo = je.getAsJsonObject();
                long valueId = jo.get("value_id").getAsLong();
                String valueInfo = jo.get("value").getAsString();
                dv.setValueId(valueId).setValue(valueInfo);
                count = count + dv.update(DetailValue.VALUE);
            }
            return ok(count);
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 描述：获取系统定义的档案属性分类列表，目的是为了提供给用户选用，单一（single）分类不能重复选用。 <br>
     * 输入：<br>
     * 输出：档案属性分类JSON数据，格式如下： <br>
     * [{type_id,keyword,name,rule,error,single}]
     * 
     * @param entityId
     * @return
     * @author dengjinye,2011-2-21
     */
    @GET
    @Path("/{entity_id}/type")
    public String getType(@PathParam("entity_id")
    long entityId)
    {
        try
        {
            Detail detail = new Detail(qr, owner);
            detail.setEntityId(entityId);
            List list = detail.getList();
            return ok(list);
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 描述：获取系统定义的档案属性分类下的属性定义，目的是为了提供给用户选用。<br>
     * 输入：<br>
     * 输出：档案属性分类JSON数据，格式如下： <br>
     * [{attribute_id,type_id,title,rule,error,datatype,opvalue}]
     * 
     * @param entityId
     * @return
     * @author dengjinye,2011-2-21
     */
    @GET
    @Path("/{entity_id}/type/{type_id}")
    public String getTypeByTypeId(@PathParam("entity_id")
    long entityId, @PathParam("type_id")
    String typeId)
    {
        try
        {
            Detail detail = new Detail(qr, owner);
            detail.setEntityId(entityId);
            if (typeId.matches("\\d+"))
            {
                detail.setTypeId(Long.parseLong(typeId));
            }
            else
            {
                Type t = new Type(qr, owner);
                t.setKeyword(typeId).load(Type.TYPE_ID);
                detail.setTypeId(t.getTypeId());
            }

            List list = detail.getList();
            return ok(list);
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 描述：通过分类ID或关键字来选用,多个type_id或keyword间用下划线“_”隔开 <br>
     * 输入：<br>
     * 输出：true成功，false失败
     * 
     * @param entityId
     * @param typeId
     *            有两种可能：type_id,keyword
     * @param value
     *            扩展属性detail_value的值，json格式
     *            eg:[{'type_id':'1','detail_value':[{'title':'档案编号','value':'12','attribute_id':'1'},{'title':'项目编号','value':'12','attribute_id':'2'}]}]
     *            add by dengjinye 20130513
     * @return
     * @author dengjinye,2011-2-22
     */
    @POST
    @Path("/{entity_id}/type/{type_id}")
    public String addByTypeId(@PathParam("entity_id")
    long entityId, @PathParam("type_id")
    String typeId,@FormParam("value")
    String value)
    {
        try
        {
            String[] typeIdOrKeyword = Format.strToStrArray(typeId, "_");
            int count = 0;
            for (int i = 0, len = typeIdOrKeyword.length; i < len; i++)
            {
                long id;
                if (typeIdOrKeyword[i].matches("\\d+"))
                {
                    id = Format.strToLong(typeIdOrKeyword[i]);
                }
                else
                {
                    Type t = new Type(qr, owner);
                    String keyword = typeIdOrKeyword[i];
                    t.setKeyword(keyword).load(Type.TYPE_ID);
                    id = t.getTypeId();
                }
                Detail detail = new Detail(qr, owner);
                long detailId = detail.setEntityId(entityId).setTypeId(id).insert();
                
                
                //新增扩展属性内容（e_datum_detail_value）add by dengjinye 20130513
                JsonParser parser = new JsonParser();
                JsonArray ja = parser.parse(value).getAsJsonArray();
                for (JsonElement je : ja)
                {
                    JsonObject jo = je.getAsJsonObject();
                    long typeIdInJson = jo.get("type_id").getAsLong();
                    if(typeIdInJson==id){
                        JsonArray detailValueJa = jo.get("detail_value").getAsJsonArray();
                        for(JsonElement je2 : detailValueJa){
                            JsonObject jo2 = je2.getAsJsonObject();
                            String title = jo2.get("title").getAsString();
                            String dvValue = jo2.get("value").getAsString();
                            long attributeId = jo2.get("attribute_id").getAsLong();
                            DetailValue dv = new DetailValue(qr, owner);
                            dv.setDetailId(detailId).setTitle(title).setValue(dvValue).setAttributeId(attributeId).insert();
                        }
                    }
                }
                
                count++;
            }
            return ok(count);
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
     * 描述：通过分类ID或关键字来删除,多个type_id或keyword间用下划线“_”隔开 <br>
     * 输入：<br>
     * 输出：true成功，false失败
     * 
     * @param entityId
     * @param typeId
     *            有两种可能：type_id,keyword
     * @return
     * @author dengjinye,2011-2-21
     */
    @DELETE
    @Path("/{entity_id}/type/{type_id}")
    public String deleteByTypeId(@PathParam("entity_id")
    long entityId, @PathParam("type_id")
    String typeId)
    {
        try
        {
            String[] typeIdOrKeyword = Format.strToStrArray(typeId, "_");
            int count = 0;
            Detail detail = new Detail(qr, owner);
            detail.setEntityId(entityId);
            for (int i = 0, len = typeIdOrKeyword.length; i < len; i++)
            {
                long id;
                if (typeIdOrKeyword[i].matches("\\d+"))
                {
                    id=Format.strToLong(typeIdOrKeyword[i]);
                }
                else
                {
                    Type t = new Type(qr, owner);
                    String keyword = typeIdOrKeyword[i];
                    t.setKeyword(keyword).load(Type.TYPE_ID);
                    id = t.getTypeId();
                }
                detail.setTypeId(id).delete();
            }
            return ok(count);
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }
}
